package gpr.view;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Http
{
	/**
	 * Returns an input stream that reads from an open HTTP connection.
	 * Notice that this is a synchronous (blocking) method.
	 * 
	 * Notice that an HttpURLConnection instance is used to make a single request
	 * but the underlying network connection to the HTTP server may be transparently shared by other instances.
	 * Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection
	 * after a request may free network resources associated with this instance but has no effect on any shared persistent connection.
	 * Calling the disconnect() method on a HttpURLConnection object may close the underlying socket
	 * if a persistent connection is otherwise idle at that time. 
	 * 
	 * @param strURL resource url
	 * @return an input stream that reads from an open HTTP connection, null if something goes wrong
	 */
	public static InputStream getHttpInputStream(String strURL)
	{
		InputStream inputStream = null;
		
		try 
		{
			URL url = new URL(strURL);

			HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();			
			httpConn.setRequestMethod("GET");
			httpConn.connect();
		
			if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)
				inputStream = httpConn.getInputStream();			
		}
		catch (Exception ex)
		{
			inputStream = null;
		}

		return inputStream;		
	}
	
	/**
	 * Returns an HTTP text resource.
	 * Notice that this is a synchronous (blocking) method.
	 * 
	 * @param strURL resource url
	 * @return response text, null if something goes wrong
	 */
	public static String getHttpText(String strURL)
	{
		StringWriter sw = null;
		
		InputStream in = getHttpInputStream(strURL);
		
		if (in != null)
		{
			try
			{
				sw = new StringWriter();
				InputStreamReader reader = new InputStreamReader(in);
				
                int count = 0;
                char[] buffer = new char[512];
                while ((count = reader.read(buffer, 0, 512)) != -1)
                    sw.write(buffer, 0, count);
			}
			catch(Exception e)
			{			
				sw = null;
			}		
			finally
			{
				try
				{
					in.close();
				}
				catch(Exception e) { }
			}
		}

		if (sw == null)
			return null;

        return sw.toString();
	}
}
